#include "unifiedexportstatemanager.h"
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QStateMachine>
#include <QState>
#include <QFinalState>
#include <QSignalTransition>

UnifiedExportStateManager::UnifiedExportStateManager(QObject* parent)
    : QObject(parent)
    , m_stateMachine(nullptr)
    , m_idleState(nullptr)
    , m_readyState(nullptr)
    , m_exportingState(nullptr)
    , m_completedState(nullptr)
    , m_failedState(nullptr)
    , m_cancelledState(nullptr)
    , m_healthCheckTimer(nullptr)
    , m_completionTimer(nullptr)
{
    // 初始化支持的文件格式
    m_supportedFormats = {"pdf", "jpg", "jpeg", "png", "bmp", "tiff"};
    
    // 设置状态机
    setupStateMachine();
    
    // 初始化定时器
    m_healthCheckTimer = new QTimer(this);
    m_healthCheckTimer->setInterval(m_healthCheckIntervalMs);
    connect(m_healthCheckTimer, &QTimer::timeout, this, &UnifiedExportStateManager::onHealthCheckTimeout);
    
    m_completionTimer = new QTimer(this);
    m_completionTimer->setSingleShot(true);
    m_completionTimer->setInterval(m_completionDelayMs);
    connect(m_completionTimer, &QTimer::timeout, this, &UnifiedExportStateManager::onCompletionTimeout);
    
}

UnifiedExportStateManager::~UnifiedExportStateManager()
{
    if (m_stateMachine) {
        m_stateMachine->stop();
    }
}

void UnifiedExportStateManager::setupStateMachine()
{
    m_stateMachine = new QStateMachine(this);
    
    // 创建状态
    createStates();
    
    // 创建转换
    createTransitions();
    
    // 设置初始状态
    m_stateMachine->setInitialState(m_idleState);
    
    // 连接状态变化信号
    connect(m_stateMachine, &QStateMachine::stateChanged, 
            this, &UnifiedExportStateManager::onStateMachineStateChanged);
    
    // 启动状态机
    m_stateMachine->start();
}

void UnifiedExportStateManager::createStates()
{
    // 创建各个状态
    m_idleState = new QState();
    m_readyState = new QState();
    m_exportingState = new QState();
    m_completedState = new QState();
    m_failedState = new QState();
    m_cancelledState = new QState();
    
    // 设置状态属性
    m_idleState->setProperty("state", static_cast<int>(ExportState::Idle));
    m_readyState->setProperty("state", static_cast<int>(ExportState::Ready));
    m_exportingState->setProperty("state", static_cast<int>(ExportState::Exporting));
    m_completedState->setProperty("state", static_cast<int>(ExportState::Completed));
    m_failedState->setProperty("state", static_cast<int>(ExportState::Failed));
    m_cancelledState->setProperty("state", static_cast<int>(ExportState::Cancelled));
    
    // 添加状态到状态机
    m_stateMachine->addState(m_idleState);
    m_stateMachine->addState(m_readyState);
    m_stateMachine->addState(m_exportingState);
    m_stateMachine->addState(m_completedState);
    m_stateMachine->addState(m_failedState);
    m_stateMachine->addState(m_cancelledState);
}

void UnifiedExportStateManager::createTransitions()
{
    // Idle -> Ready (文件添加)
    m_idleState->addTransition(this, &UnifiedExportStateManager::filesAdded, m_readyState);
    
    // Ready -> Exporting (开始导出)
    m_readyState->addTransition(this, &UnifiedExportStateManager::exportStarted, m_exportingState);
    
    // Ready -> Idle (文件移除)
    m_readyState->addTransition(this, &UnifiedExportStateManager::filesRemoved, m_idleState);
    
    // Exporting -> Completed (导出完成)
    m_exportingState->addTransition(this, &UnifiedExportStateManager::exportCompleted, m_completedState);
    
    // Exporting -> Failed (导出失败)
    m_exportingState->addTransition(this, &UnifiedExportStateManager::exportFailed, m_failedState);
    
    // Exporting -> Cancelled (导出取消)
    m_exportingState->addTransition(this, &UnifiedExportStateManager::exportCancelled, m_cancelledState);
    
    // Completed -> Ready (自动回到就绪状态)
    m_completedState->addTransition(m_completionTimer, &QTimer::timeout, m_readyState);
    
    // Failed -> Ready (重试)
    m_failedState->addTransition(this, &UnifiedExportStateManager::retryRequested, m_readyState);
    
    // Cancelled -> Ready (重新开始)
    m_cancelledState->addTransition(this, &UnifiedExportStateManager::filesAdded, m_readyState);
}

void UnifiedExportStateManager::setFiles(const QStringList& filePaths)
{
    m_filePaths = filePaths;
    
    // 验证文件
    QList<FileValidationResult> results;
    bool hasValidFiles = false;
    
    for (const QString& filePath : filePaths) {
        FileValidationResult result = validateFile(filePath);
        results.append(result);
        
        if (result.isValid) {
            hasValidFiles = true;
        } else {
            emit fileValidationFailed(filePath, result.error);
        }
    }
    
    emit filesValidated(results);
    
    // 更新文件状态
    if (hasValidFiles) {
        updateFileState(FileState::HasFiles);
        emit filesAdded();
    } else {
        updateFileState(FileState::NoFiles);
    }
}

void UnifiedExportStateManager::addFile(const QString& filePath)
{
    if (!m_filePaths.contains(filePath)) {
        m_filePaths.append(filePath);
        
        FileValidationResult result = validateFile(filePath);
        if (result.isValid) {
            updateFileState(FileState::HasFiles);
            emit filesAdded();
        } else {
            emit fileValidationFailed(filePath, result.error);
        }
    }
}

void UnifiedExportStateManager::removeFile(const QString& filePath)
{
    if (m_filePaths.removeOne(filePath)) {
        if (m_filePaths.isEmpty()) {
            updateFileState(FileState::NoFiles);
            emit filesRemoved();
        }
    }
}

void UnifiedExportStateManager::clearFiles()
{
    m_filePaths.clear();
    updateFileState(FileState::NoFiles);
    emit filesRemoved();
}

void UnifiedExportStateManager::startExport()
{
    if (!canExport()) {
        return;
    }
    
    m_context.startTime = QDateTime::currentDateTime();
    m_context.totalFiles = m_filePaths.size();
    m_context.completedFiles = 0;
    m_context.currentStatus = "准备导出...";
    
    updateContext();
    emit exportStarted(m_context.totalFiles);
    emit exportStarted(m_context.totalFiles);
}

void UnifiedExportStateManager::updateProgress(int completed, int total, const QString& status)
{
    if (m_context.state != ExportState::Exporting) {
        return;
    }
    
    m_context.completedFiles = completed;
    m_context.totalFiles = total;
    m_context.currentStatus = status;
    
    updateContext();
    emit exportProgressChanged(completed, total, status);
    
    // 检查是否完成
    if (completed >= total) {
        completeExport();
    }
}

void UnifiedExportStateManager::completeExport()
{
    m_context.endTime = QDateTime::currentDateTime();
    m_context.currentStatus = "导出完成";
    
    updateState(ExportState::Completed);
    updateContext();
    emit exportCompleted();
    emit exportCompleted();
    
    // 启动完成定时器
    m_completionTimer->start();
}

void UnifiedExportStateManager::failExport(const QString& error)
{
    m_context.errorMessage = error;
    m_context.currentStatus = "导出失败";
    
    updateState(ExportState::Failed);
    updateContext();
    
    ExportError exportError = analyzeError(error);
    emit exportFailed(error);
    emit errorOccurred(exportError);
}

void UnifiedExportStateManager::cancelExport()
{
    m_context.currentStatus = "导出已取消";
    
    updateState(ExportState::Cancelled);
    updateContext();
    emit exportCancelled();
}

void UnifiedExportStateManager::setSupportedFormats(const QStringList& formats)
{
    m_supportedFormats = formats;
    m_context.supportedFormats = formats;
}

void UnifiedExportStateManager::setCompletionDelay(int delayMs)
{
    m_completionDelayMs = delayMs;
    m_completionTimer->setInterval(delayMs);
}

void UnifiedExportStateManager::setHealthCheckInterval(int intervalMs)
{
    m_healthCheckIntervalMs = intervalMs;
    m_healthCheckTimer->setInterval(intervalMs);
}

UnifiedExportStateManager::ExportError UnifiedExportStateManager::analyzeError(const QString& errorMessage) const
{
    ExportError error;
    
    if (errorMessage.contains("权限") || errorMessage.contains("permission")) {
        error = ExportError::createError("PERMISSION_DENIED", "没有文件访问权限", "请检查文件权限或选择其他文件", true);
        error.severity = ErrorSeverity::Error;
    } else if (errorMessage.contains("格式") || errorMessage.contains("format")) {
        error = ExportError::createError("UNSUPPORTED_FORMAT", "不支持的文件格式", "请选择PDF或图片文件", false);
        error.severity = ErrorSeverity::Warning;
    } else if (errorMessage.contains("空间") || errorMessage.contains("space")) {
        error = ExportError::createError("INSUFFICIENT_SPACE", "磁盘空间不足", "请清理磁盘空间后重试", true);
        error.severity = ErrorSeverity::Error;
    } else {
        error = ExportError::createError("UNKNOWN_ERROR", errorMessage, "请重试或联系技术支持", true);
        error.severity = ErrorSeverity::Error;
    }
    
    return error;
}

void UnifiedExportStateManager::handleError(const ExportError& error)
{
    emit errorOccurred(error);
}

UnifiedExportStateManager::FileValidationResult UnifiedExportStateManager::validateFile(const QString& filePath) const
{
    QFileInfo fileInfo(filePath);
    
    // 检查文件是否存在
    if (!fileInfo.exists()) {
        return FileValidationResult::createError("文件不存在");
    }
    
    // 检查文件是否可读
    if (!fileInfo.isReadable()) {
        return FileValidationResult::createError("文件不可读");
    }
    
    // 检查文件大小
    if (fileInfo.size() == 0) {
        return FileValidationResult::createError("文件为空");
    }
    
    // 检查文件格式
    if (!isFileSupported(filePath)) {
        return FileValidationResult::createError("不支持的文件格式");
    }
    
    // 检查文件类型
    FileType fileType = detectFileType(filePath);
    if (fileType == FileType::Unknown) {
        return FileValidationResult::createError("无法识别的文件类型");
    }
    
    return FileValidationResult::createSuccess(fileType, fileInfo.size(), fileInfo.lastModified());
}

UnifiedExportStateManager::FileType UnifiedExportStateManager::detectFileType(const QString& filePath) const
{
    QString suffix = QFileInfo(filePath).suffix().toLower();
    
    if (suffix == "pdf") return FileType::PDF;
    if (suffix == "jpg" || suffix == "jpeg") return FileType::Image;
    if (suffix == "png") return FileType::Image;
    if (suffix == "bmp") return FileType::Image;
    if (suffix == "tiff" || suffix == "tif") return FileType::Image;
    if (suffix == "txt") return FileType::Text;
    
    return FileType::Unknown;
}

bool UnifiedExportStateManager::isFileSupported(const QString& filePath) const
{
    QString suffix = QFileInfo(filePath).suffix().toLower();
    return m_supportedFormats.contains(suffix);
}

void UnifiedExportStateManager::updateState(ExportState newState)
{
    if (m_context.state != newState) {
        ExportState oldState = m_context.state;
        m_context.state = newState;
        
        logStateChange(oldState, newState);
        emitStateChangeSignals(newState, oldState);
    }
}

void UnifiedExportStateManager::updateFileState(FileState newState)
{
    if (m_context.fileState != newState) {
        FileState oldState = m_context.fileState;
        m_context.fileState = newState;
        
        
        emit fileStateChanged(newState);
    }
}

void UnifiedExportStateManager::updateContext()
{
    emit contextChanged(m_context);
}

void UnifiedExportStateManager::logStateChange(ExportState from, ExportState to)
{
}

void UnifiedExportStateManager::emitStateChangeSignals(ExportState newState, ExportState oldState)
{
    emit stateChanged(newState, oldState);
    updateContext();
}

void UnifiedExportStateManager::onStateMachineStateChanged()
{
    // 状态机状态变化处理
}

void UnifiedExportStateManager::onHealthCheckTimeout()
{
    // 健康检查超时处理
    if (m_context.isExporting()) {
    }
}

void UnifiedExportStateManager::onCompletionTimeout()
{
    // 完成超时处理
}
